<template>
  <div class="audio green-audio-player">
    <div class="loading" v-if="!isPlay">
      <div class="spinner" :style="{ backgroundImage: 'url(' + spinnerImage + ')' }"></div>
    </div>
    <div class="play-pause-btn" v-if="isPlay" @click="togglePlay">
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="24" viewBox="0 0 18 24">
        <path fill="#566574" fill-rule="evenodd" :d="playPauseIcon" class="play-pause-icon" id="playPause"/>
      </svg>
    </div>
    <div class="controls">
      <span class="time-label current-time">{{currentTime}}</span>
      <div class="slider" data-direction="horizontal" @click="rewind">
        <div class="progress" :style="progressStyle">
          <div class="pin" id="progress-pin" data-method="rewind" @touchstart="rewindStart" @touchend="rewindEnd"
               @touchmove="rewind"></div>
        </div>
      </div>
      <span class="time-label total-time">{{totalTime}}</span>
    </div>

    <audio ref="player"
           @timeupdate="updateProgress"
           @volumechange="updateVolume"
           @loadedmetadata="metaDataLoaded"
           @canplay="makePlay"
           @ended="playEnded">
      <source :src="source" type="audio/mpeg">
    </audio>
  </div>
</template>
<script>
import loading from "./loading.png";
import { mapGetters } from "vuex";
export default {
  props: {
    source: String
  },
  created() {},
  mounted() {
    this.$watch("source", val => {
      console.log(val);
      this.playPauseIcon = this.playIcon;
      this.$refs.player.load();
    });
  },
  activated() {
    this.progressPercent = 0;
    //      this.currentTime = '0:00'
    //      this.totalTime = '0.00'
    //      this.duration = 0
  },
  data() {
    return {
      isPlay: true,
      pausedIcon: "M0 0h6v24H0zM12 0h6v24h-6z",
      playIcon: "M18 12L0 24V0",
      playPauseIcon: "M18 12L0 24V0",
      progressPercent: 0,
      currentTime: "0:00",
      totalTime: "0.00",
      duration: 0,
      draggableClasses: ["pin"],
      currentlyDragged: null,
      loading: loading
    };
  },
  computed: {
    ...mapGetters({}),
    spinnerImage() {
      return this.loading;
    },
    // isDraggable () {},
    progressStyle() {
      return { width: `${this.progressPercent}%` };
    }
  },
  methods: {
    updateProgress() {
      if (this.$refs.player) {
        var current = this.$refs.player.currentTime;
        this.progressPercent = Math.ceil((current / this.duration) * 100);
        this.currentTime = this.formatTime(current);
      }
    },
    updateVolume() {
      //        console.log('update volume')
    },
    inRange(event) {
      const rangeBox = this.getRangeBox(event);
      const rect = rangeBox.getBoundingClientRect();
      const direction = rangeBox.dataset.direction;
      if (direction === "horizontal") {
        var min = rangeBox.offsetLeft;
        var max = min + rangeBox.offsetWidth;
        if (event.type === "click") {
          if (event.clientX < min || event.clientX > max) return false;
        } else {
          if (event.touches[0].clientX < min || event.touches[0].clientX > max)
            return false;
        }
      } else {
        min = rect.top;
        max = min + rangeBox.offsetHeight;
        if (event.clientY < min || event.clientY > max) return false;
      }
      return true;
    },
    getRangeBox(event) {
      let rangeBox = event.target;

      const el = this.currentlyDragged;
      if (event.type === "click") {
        return rangeBox;
      } else {
        rangeBox = el.parentElement.parentElement;
      }

      return rangeBox;
    },
    getCoefficient(event) {
      const slider = this.getRangeBox(event);
      const rect = slider.getBoundingClientRect();
      let K = 0;
      if (slider.dataset.direction === "horizontal") {
        let offsetX = 0;
        if (event.type === "click") {
          offsetX = event.clientX - slider.offsetLeft;
        } else {
          offsetX = event.touches[0].clientX - slider.offsetLeft;
        }
        const width = slider.clientWidth;
        K = offsetX / width;
      } else if (slider.dataset.direction === "vertical") {
        const height = slider.clientHeight;
        var offsetY = event.clientY - rect.top;
        K = 1 - offsetY / height;
      }
      return K;
    },
    rewind(event) {
      if (this.inRange(event)) {
        this.$refs.player.currentTime =
          this.$refs.player.duration * this.getCoefficient(event);
      }
    },
    changeVolume() {},
    formatTime(time) {
      var min = Math.floor(time / 60);
      var sec = Math.floor(time % 60);
      return min + ":" + (sec < 10 ? "0" + sec : sec);
    },
    togglePlay() {
      if (this.$refs.player.paused) {
        this.playPauseIcon = this.pausedIcon;
        this.$refs.player.play();
      } else {
        this.playPauseIcon = this.playIcon;
        this.$refs.player.pause();
      }
    },
    makePlay() {
      //        console.log('can play make play')
      this.isPlay = true;
    },
    directionAware() {},
    metaDataLoaded() {
      //        console.log('meta Data Loaded')
      this.duration = this.$refs.player.duration;
      this.totalTime = this.formatTime(this.$refs.player.duration);
    },
    playEnded() {
      this.playPauseIcon = this.playIcon;
      this.$refs.player.currentTime = 0;
    },
    rewindStart(event) {
      //        console.log('touch start')
      this.currentlyDragged = event.target;
    },
    rewindEnd() {
      //        console.log('touch end')
      this.currentlyDragged = false;
    }
  },
  components: {}
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
